use chrono::{DateTime, Local};
use tabled::{settings::{location::ByColumnName, object::Rows, Color, Remove, Style}, Table, Tabled};
use uuid::Uuid;

#[derive(Default, Tabled)]
pub(crate) struct History {
    #[tabled(rename = "ID")]
    pub id: String,
    #[tabled(rename = "App")]
    pub app: String,
    #[tabled(rename = "Pattern")]
    pub pattern: String,
    #[tabled(rename = "Password")]
    pub password: String,
    #[tabled(rename = "Remark")]
    pub remark: String,
    #[tabled(display("display_time"), rename = "CreateTime")]
    pub create_time: DateTime<Local>,
}

fn display_time(time: &DateTime<Local>) -> String {
    time.format("%Y/%m/%d %H:%M:%S").to_string()
}

impl History {
    pub fn new(app: &str, pattern: &str, password: &str, remark: &str) -> Self {
        History {
            id: Uuid::new_v4().to_string(),
            app: app.to_string(),
            pattern: pattern.to_string(),
            password: password.to_string(),
            remark: remark.to_string(),
            create_time: Local::now(),
        }
    }

    pub fn print_historys(historys: &Vec<History>, show_id: bool, show_pattern: bool) {
        let mut table = Table::new(historys);
        table.with(Style::modern());
        table.modify(Rows::first(), Color::FG_BRIGHT_GREEN);
        if !show_id {
            table.with(Remove::column(ByColumnName::new("ID")));
        }
        if !show_pattern {
            table.with(Remove::column(ByColumnName::new("Pattern")));
        }
        println!("{}", table);
    }
}
